<template>
  <div>
    <h1>{{id ? '修改' : '新建'}}文章</h1>
    <el-form label-width="100px" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" multiple>
          <el-option v-for="item in categories" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <vue-editor v-model="model.body" useCustomImageHandler @image-added="handleImageAdded"/>
      </el-form-item>
      <el-form-item style="margin-top:1rem">
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'

export default {
  props: {
    id: String
  },
  data () {
    return {
      model: {},
      categories: []
    }
  },
  components: {
    VueEditor
  },
  methods: {
    async save () {
      if (this.model.title.trim() === '') {
        this.$message.error('请输入文章标题')
        return
      }
      if (this.id) {
        await this.$http.put(`/rest/articles/${this.id}`, this.model)
        this.$message.success('修改成功')
      } else {
        await this.$http.post('/rest/articles', this.model)
        this.$message.success('保存成功')
      }
      this.$router.push('/articles/list')
    },
    async getName () {
      const { data: res } = await this.$http.get(`/rest/articles/${this.id}`)
      this.model = Object.assign({}, this.model, res)
    },
    async getCategories () {
      const { data: res } = await this.$http.get('/rest/categories')
      this.categories = res.filter(item => item.parent && item.parent.name === '新闻资讯')
    },
    async handleImageAdded (file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData()
      formData.append('file', file)
      const { data: res } = await this.$http.post('/upload', formData)
      Editor.insertEmbed(cursorLocation, 'image', res.url)
      resetUploader()
    }
  },
  created () {
    this.id && this.getName()
    this.getCategories()
  }
}
</script>

<style>
</style>
